#!/bin/sh

. /usr/share/common

if [ -z "$MDEV" ]; then
	echo_error "No device name to mount!"
	exit 1
fi

device_node="/dev/$MDEV"
echo_info "Device node: $device_node"

mount_point="/mnt/$MDEV"
echo_info "Mount point: $mount_point"

diag="$mount_point/.diag"
run="$mount_point/run.sh"
run_once="$mount_point/runonce.sh"
run_once_flag="${run_once/.sh/.done}"

#log() {
#	logger -p daemon.info -t automount[$$] -s "$1"
#}

cleanup() {
	if [ -d "$mount_point" ]; then
		if rm -r "$mount_point"; then
			echo_info "Removed mount point $mount_point"
		else
			echo_warning "Failed to remove mount point $mount_point"
		fi
	else
		echo_info "No mount point $mount_point found"
	fi
}

do_fsck() {
	res=$(fsck -V -y "$device_node" 2>&1)
	fsck_status=$?

	echo "$res" | while IFS= read -r line; do
		echo_info "$line"
	done

	if [ "$fsck_status" -eq 0 ]; then
		echo_info "fsck check succeeded on $device_node"
	else
		echo_warning "fsck check failed on $device_node"

		if [ "$fsck_status" -eq 8 ] || [ "$fsck_status" -eq 16 ] || \
		  [ "$fsck_status" -eq 32 ] || [ "$fsck_status" -eq 128 ]; then
			echo_warning "Critical fsck error with exit status $fsck_status, mounting process aborted"
			return 1
		else
			echo_warning "Non-critical fsck error with exit status $fsck_status, continuing"
		fi
	fi
}

do_mount() {
	if mkdir -p "$mount_point"; then
		echo_info "Created mount point $mount_point"
	else
		echo_warning "Cannot create mount point $mount_point"
		return 1
	fi

	if ! do_fsck; then
		echo_warning "Failed to fsck $device_node"
		return 1
	fi

	if mount -t auto -o noatime,sync "$device_node" "$mount_point"; then
		echo_info "Mounted $device_node to $mount_point"
	else
		echo_warning "Failed to mount $device_node to $mount_point"
		cleanup
		return 1
	fi

	[ -f "$diag" ] && do_run_diag
	[ -f "$run_once" ] && do_run_once
	[ -f "$run" ] && do_run_always
}

do_umount() {
	if lsof | grep -q "$mount_point"; then
		echo_info "Killing processes that are using $mount_point"
		lsof | awk "/$mount_point/{print \$1}" | xargs kill -9
	else
		echo_info "No processes are using $mount_point"
	fi

	if grep -qs "^$device_node " /proc/mounts; then
		if umount -l "$mount_point"; then
			echo_info "Unmounted $mount_point"
		else
			echo_warning "Failed to unmount $mount_point"
		fi
	else
		echo_info "$device_node is not mounted"
	fi

	cleanup
}

do_run_always() {
	if sh $run; then
		echo_info "Executed $run script"
	else
		echo_warning "Failed to execute $run script"
	fi
}

do_run_diag() {
	rm -f $mount_point/.diag
	thingino-diag -l $mount_point
	sync
	do_umount
	play -l 3 /usr/share/sounds/th-chime_1.opus
}

do_run_once() {
	if [ -f "$run_once_flag" ]; then
		echo_warning "Stop flag $run_once_flag exists"
		return 1
	fi

	if sh "$run_once"; then
		touch "$run_once_flag"
		echo_info "Executed $run_once script"
	else
		echo_warning "Failed to execute $run_once script"
	fi
}

case "$ACTION" in
	add | "")
		do_umount
		do_mount
		;;
	remove)
		do_umount
		;;
esac

exit 0
